package com.xj.driver.mqtt.subscriber;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xj.common.bean.constant.Common;
import com.xj.common.bean.em.ControlStateEm;
import com.xj.common.bean.point.PointValue;
import com.xj.common.model.ControlInfo;
import com.xj.common.sdk.bean.driver.DriverContext;
import com.xj.common.sdk.service.DriverService;
import com.xj.common.utils.JsonPaseUtil;
import com.xj.driver.mqtt.bean.MqttHeaderB;
import com.xj.driver.mqtt.service.StateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName : MqttDeviceRegister
 * @Description : 设备接入
 * @Author : Alan
 * @Date: 2020-09-08 15:37
 */
@Slf4j
@Component
public class MqttDeviceHandler implements MessageHandler {


    @Resource
    private DriverService driverService;
    @Resource
    private StateService stateService;
    @Resource
    private DriverContext driverContext;
    @ServiceActivator(inputChannel = "topic-device")
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {

        log.info("设备信息信息:{}",message);
        String payload = (String) message.getPayload();
        MessageHeaders headers = message.getHeaders();

        String mqttReceivedTopic = headers.get("mqtt_receivedTopic", String.class);

        //先解析出重要信息 根据topic分别进行消息处理
        /*解析出订阅主题*/
        String command = mqttReceivedTopic.substring(mqttReceivedTopic.lastIndexOf("/")+1);
        Object test = mqttReceivedTopic.split("/")[2];
        long deviceId = driverContext.getDriverMetadata().getDeviceSnMap().get(mqttReceivedTopic.split("/")[2]).getId();
        JSONObject jo = (JSONObject)JSON.parse(payload);
        JSONObject joHeader = jo.getJSONObject("header");
        String dataBody = jo.getJSONObject("dataBody").toJSONString();
        MqttHeaderB header = getHeaderB(joHeader);
        switch (command){
            case "response": {doResponse(dataBody,header,deviceId); break;}
            case "state": {doState(dataBody,header,deviceId); break;}
            case "event": {doEvent(dataBody,header,deviceId); break;}
            default:{
                log.info("暂不支持的主题操作:{}",command);
            }
        }

        /*String payload = (String) message.getPayload();
        MessageHeaders headers = message.getHeaders();

        JSONObject payloadJson = JSONObject.parseObject(payload);

        log.info("发送pointvalue到kafka上");
        PointValue pointValue = new PointValue();
        pointValue.setCalculateValue(123);
        pointValue.setCreateTime(new Date());
        pointValue.setDeviceId(12l);
        pointValue.setPointId(121l);
        pointValue.setRawValue("10.0");
        pointValue.setUnit("C");
        pointValue.setValue("123");
        pointValue.setOriginTime(new Date());

        driverService.pointValueSender(pointValue);
        String commandType = payloadJson.getString("type");
        String mqttReceivedTopic = headers.get("mqtt_receivedTopic", String.class);
        String command = mqttReceivedTopic.substring(mqttReceivedTopic.lastIndexOf("/")+1);


        switch (commandType){


            default:{
                log.info("暂不支持的主题操作:{}",commandType);
            }

        }*/
    }

    private void doState(String payload, MqttHeaderB header,long deviceId){
        log.info("设备上送状态信息处理:{}",payload,header);
        if(!checkVersion(header.getVersion()))
            return ;
        //解析实时数据，上传到平台
        //处理实时数据信息信息，根据不同的funtcion进行不同的处理
        String function = header.getFunction();
        switch (function){
            case "ChargeingData": {
                stateService.doChargeState(deviceId,payload);
                break;
            }
            default:{
                log.info("暂不识别的控制操作",function);
            }

        }
    }
    private void doEvent(String payload,MqttHeaderB header,long deviceId){
        log.info("设备上送事件信息处理:{}",payload,header);
        if(!checkVersion(header.getVersion()))
            return ;

        //处理事件数据信息信息，根据不同的funtcion进行不同的处理
        String function = header.getFunction();
        switch (function){
            case "ChargeEvent": {
                stateService.doChargeState(deviceId,payload);
                break;
            }
            default:{
                log.info("暂不识别的控制操作",function);
            }

        }
        //发送事件信息，进行存储
        /*问题3：为什么设备事件是空的*/
        driverService.deviceEventSender(null);
    }
    private void doResponse(String payload,MqttHeaderB header,long deviceId){
        log.info("设备控制回复信息处理:{}",payload,header);
        if(!checkVersion(header.getVersion()))
            return ;
        //处理回复信息信息，根据不同的funtcion进行不同的处理
        String function = header.getFunction();
        switch (function){
            case "remoteChargeStarResp": {doRemoteChargeStartResp( payload ,  header, deviceId); break;}
            default:{
                log.info("暂不识别的控制操作",function);
            }

        }
    }

    //上送设备回复开启远程充电信息到物联网平台
    private void doRemoteChargeStartResp(String payload , MqttHeaderB header,long deviceID){
        ControlInfo controlInfo = new ControlInfo();
        controlInfo.setResptime(new Date());
        controlInfo.setResultcode(ControlStateEm.CTL_STATE_RESPONSE.getCode());
        controlInfo.setResultmsg(ControlStateEm.CTL_STATE_RESPONSE.getMsg()+":"+payload);
        controlInfo.setId(header.getIndex().toString());
        controlInfo.setDeviceId(deviceID);
        controlInfo.setMsgType(Common.Device.ControlEvent.RESPONSE);
        driverService.controlInfoSender(controlInfo);
    }

    private MqttHeaderB getHeaderB(JSONObject  joHeader){

        MqttHeaderB mhb = new MqttHeaderB();
        mhb.setFunction(joHeader.getString("function"));
        mhb.setIndex(joHeader.getLong("index"));
        mhb.setReason(joHeader.getInteger("reason"));
        mhb.setTimestamp(new Date(System.currentTimeMillis()).toString());
        mhb.setVersion(joHeader.getString("version"));
        return mhb;
    }
    private boolean checkVersion(String version ){
        //校验版本
        if(!version.equals("V1.0")) {
            log.error("Version Error :" + version);
            return false ;
        }
        return true;
    }
}
